import pandas as pd
import plotly.express as px
import plotly.io as pio

# 设置专业商务风格
pio.templates.default = "plotly_white"

# 读取数据（替换为你的CSV文件路径）
df = pd.read_excel("C:\\Users\\24424\\Desktop\\各汽车厂商各车型分月度销售量排名及售价数据2015-202309.xlsx")

# 筛选2023年9月数据
df_sep = df[(df['年份'] == 2023) & (df['月份'] == 9)]

# 定义价格区间和车型类别映射
def map_price_segment(price_str):
    try:
        min_price = float(str(price_str).split('-')[0])
        if min_price < 10:
            return "10万以下"
        elif 10 <= min_price < 20:
            return "10-20万"
        elif 20 <= min_price < 30:
            return "20-30万"
        else:
            return "30万以上"
    except:
        return "未知价格"

def map_vehicle_type(model):
    model = str(model).lower()
    if 'suv' in model or '越野' in model or '跨界' in model:
        return "SUV/越野车"
    elif '轿车' in model or 'sedan' in model or '朗逸' in model or '轩逸' in model:
        return "轿车"
    elif '新能源' in model or '电动' in model or '混动' in model or 'EV' in model or 'PHEV' in model:
        return "新能源车"
    elif 'MPV' in model or '商务' in model or 'GL8' in model:
        return "MPV/商务车"
    else:
        return "其他车型"

# 应用映射
df_sep['价格区间'] = df_sep['售价（万元）'].apply(map_price_segment)
df_sep['车型类别'] = df_sep['车型'].apply(map_vehicle_type)

# 聚合数据
agg_df = df_sep.groupby(['价格区间', '车型类别'])['销量'].sum().reset_index()

# 创建旭日图
fig = px.sunburst(
    agg_df,
    path=['价格区间', '车型类别'],
    values='销量',
    color='价格区间',
    color_discrete_map={
        "10万以下": "#FF9AA2",
        "10-20万": "#FFB7B2",
        "20-30万": "#FFDAC1",
        "30万以上": "#E2F0CB"
    },
    hover_data=['销量'],
    branchvalues='total',
    maxdepth=2,
    title='2023年9月汽车市场销量分布<br><sup>按价格区间和车型类别分析</sup>'
)

# 添加装饰元素和样式调整
fig.update_layout(
    font_family="Arial",
    title_font_size=24,
    title_x=0.5,
    margin=dict(t=100, l=0, r=0, b=0),
    annotations=[
        dict(
            text="数据来源：中国汽车分车型每月销售量",
            showarrow=False,
            xref="paper",
            yref="paper",
            x=0.5,
            y=-0.1,
            font_size=10
        )
    ]
)

# 添加自定义悬停信息
fig.update_traces(
    hovertemplate="<b>%{label}</b><br>销量: %{value:,}辆<br>占比: %{percentParent:.1%}",
    textinfo="label+percent parent"
)

# 添加环形刻度标签
fig.update_traces(
    insidetextorientation='radial',
    textfont_size=14
)

# 添加中心注释
fig.add_annotation(
    text=f"总销量<br>{df_sep['销量'].sum():,}辆",
    x=0.5,
    y=0.5,
    showarrow=False,
    font_size=16,
    font_color="#333333"
)
# 显示图表
fig.show()
# 保存为HTML文件
fig.write_html("price_segment_sunburst.html")